<?php
use C\Config_App;
use I\App;
use I\DB;
use M\Middle_Public;

class Controller extends Middle_Public {
    // /api/get_list?user_id=106&timestamp=1588853158&sign=7b941b7afc66c99cd597b22b2d80e7fd
    public function checkAuth() {

    }

    public function is($dbname, $id, $pro = 0) {
        $db = DB::write();
        $sql = "select * from {$dbname}.tasks where id = $id";
        $a   = $db->query($sql);
        if (count($a) == 0) {
            echo 1;exit();
        }
        $task = $a[0];

        if ($pro && $task->pro != $pro) {
            echo 2;exit();
        }
        if ($task->status < 30) {
            echo 0;
        } else {
            echo 5;
        }
    }


    public function get_list() {
        $user_id = getgpc('user_id');
        $curpage = getgpc('page', 1);
        $perpage = getgpc('perpage', 20);

        $db = DB::write();

        $sqlcount = 'select count(*) as num from tasks ';
        $where    = 'where leader = ' . $user_id;

        $status = getgpc('status', 0);
        if ($status == 0) {
            $where .= ' and status < 30';
        } elseif ($status == 1) {
            $where .= ' and status < 60';
        } elseif ($status == 2) {
            $where .= ' and status >= 60';
        }

        $count_row = $db->row($sqlcount . $where);
        $totalnum  = $count_row->num;

        $offset = page_get_start($curpage, $perpage, $totalnum);
        $sql    = sprintf('select id, title, content, tester, caty, priority, status, pro, tag, deadline from tasks %s order by status, priority desc limit %s offset %s', $where, $perpage, $offset);

        $tasks = $db->query($sql);

        $res = [
            'list'      => $db->query($sql),
            'totalnum'  => $totalnum,
            'curpage'   => $curpage,
            'perpage'   => $perpage,
            'status'    => App::singleton()->getconfig('worktime', 'status'),
            'prioritys' => App::singleton()->getconfig('worktime', 'priority'),
            'tags'      => DB::keyBy("select id, name, pro from tags"),
            'pros'      => DB::keyBy("select * from pros"),
            'users'     => DB::keyBy("select id, name, department from users"),
            'catys'     => DB::keyBy("select * from titles where caty = " . App::singleton()->getconfig('worktime', 'caty')),
        ];

        echo json_encode($res, JSON_UNESCAPED_UNICODE);
    }

    public function get_pro() {
        $pros = DB::write()->query("select * from pros");
        echo json_encode($pros, JSON_UNESCAPED_UNICODE);
    }

    public function modify_status() {
        $ids = getgpc('ids');
        DB::write()->query("update tasks set status = 30 where id in($ids)");
        echo 1;
    }

}
